#include "smoothcurvewidget.h"

#include <QPainter>
#include <QtGlobal>
#include <QDateTime>

#include <smoothcurvegenerator.h>

SmoothCurveWidget::SmoothCurveWidget ( QWidget* parent ) : QWidget ( parent )
{
    showKnots = false;
    generatorMethod = 2;
}


void SmoothCurveWidget::paintEvent ( QPaintEvent* event )
{
    QPainter painter ( this );
    painter.setRenderHint ( QPainter::Antialiasing );

    //[-100, 100] [-100, 100]
    painter.translate ( width() / 2, height() / 2 );
    painter.scale ( width() / 200, height() / 200 );

    // 画坐标轴
    painter.setPen ( QColor ( 180, 180, 180 ) );
    painter.drawLine ( -100, 0, 100, 0 );
    //painter.drawLine ( 0, -100, 0, 100 );
    // showSmoothCurveCheckBox 被选中时显示平滑曲线，否则显示非平滑曲线
    painter.setPen ( QPen ( QColor ( 80, 80, 80 ), 2 ) );

    if ( generatorMethod == 1 )
    {
        painter.drawPath ( smoothCurve1 );
    }
    else if ( generatorMethod == 2 )
    {
        painter.drawPath ( smoothCurve2 );
    }
    else
    {
        painter.drawPath ( nonSmoothCurve );
    }

    // 如果曲线上的点可见，则显示出来
    if ( showKnots )
    {
        painter.setPen ( Qt::black );
        painter.setBrush ( Qt::gray );

        foreach ( QPointF p, knots )
        {
            painter.drawEllipse ( p, 3, 3 );
        }
    }
}

void SmoothCurveWidget::generateCurves()
{
    /*
    qsrand ( QDateTime::currentDateTime().toMSecsSinceEpoch() );
    // 随机生成曲线上的点: 横坐标为 [-200, 200]，纵坐标为 [-100, 100]
    int x = -200;
    knots.clear();

    //[x, y]组
    while ( x < 200 )
    {
        knots << QPointF ( x, qrand() % 200 - 100 );
        x += qMin ( qrand() % 30 + 5, 200 );
    }
    */
    if ( knots.size() <= 0 )
        return;

    // 根据曲线上的点创建平滑曲线
    smoothCurve1 = SmoothCurveGenerator1::generateSmoothCurve ( knots );
    smoothCurve2 = SmoothCurveGenerator2::generateSmoothCurve ( knots );
    // 连接点创建非平滑曲线曲线
    nonSmoothCurve = QPainterPath();
    nonSmoothCurve.moveTo ( knots[0] );

    for ( int i = 1; i < knots.size(); ++i )
    {
        nonSmoothCurve.lineTo ( knots[i] );
    }

    update();
}
